package com.xwdeshj.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;

/**
 * @author wgl
 * @date 2016-9-01
 * @class 常用公共类
 */
public class StringUtil {
    /*
     * 若obj为空值时，赋予一个默认值defaultvalue
     */
    public static String StrNoHtml(Object obj, String defaultvalue) {
        String str = "";
        try {
            str = obj.toString();
        } catch (Exception e) {
        }
        String str2 = "";

        if (new Integer(str.length()).equals(0)) {
            str2 = defaultvalue;
        } else {
            str = str.replace("\\\"", "&quot;");
            str = str.replace("<", "&lt;");
            str = str.replace(">", "&gt;");
            str = str.replace("\"", "&quot;");
            str = str.replace("'", "&#39;");
            str2 = str;
        }
        return str2;
    }

    public static String StrBackHtml(Object obj, String defaultvalue) {
        String str = "";
        try {
            str = obj.toString();
        } catch (Exception e) {
        }
        String str2 = "";

        if (new Integer(str.length()).equals(0)) {
            str2 = defaultvalue;
        } else {
            str = str.replace("&lt;", "<");
            str = str.replace("&gt;", ">");
            str = str.replace("&quot;", "\"");
            str = str.replace("&#39;", "'");
            str2 = str;
        }
        return str2;
    }

    /*
     * 获取客户端IP
     */
    public static String getIP(HttpServletRequest request) {
        String ipAddress = null;
        //ipAddress = this.getRequest().getRemoteAddr();
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }

        }

        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /*
     * 获取IP所在地信息
     */
//    public static String getCity(String IP) {
//        IPSeeker ips = IPSeeker.getInstance();
//        return ips.getCountry(IP);
//    }

    /*
     * 获取当前时间（数据库格式）
     */
    public static String getCurrentTime() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        return dateFormat.format(now);
    }

    public static String getCurrentTime30() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        Date today = new Date();
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(theCa.DAY_OF_MONTH, -30);//最后一个数字30可改，30天的意思
        Date start = theCa.getTime();
        String startDate = sdf.format(start);
        return startDate;
    }

    public static String getCurrentTime30after() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        Date today = new Date();
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(theCa.DATE, 30);//最后一个数字30可改，30天的意思
        Date start = theCa.getTime();
        String startDate = sdf.format(start);
        return startDate;
    }

    public static String getpt(Date date) throws Exception {
        SimpleDateFormat sfd2 = new SimpleDateFormat("yyyyMMdd");
        return sfd2.format(date);
    }

    public static String getpt7(Date date) throws Exception {
        SimpleDateFormat sfd2 = new SimpleDateFormat("yyyyMMdd");
        Date today = new Date();
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(theCa.DATE, -7);//最后一个数字30可改，30天的意思
        Date start = theCa.getTime();
        return sfd2.format(start);
    }

    public static String getptall(Date date) throws Exception {
        SimpleDateFormat sfd2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sfd2.format(date);
    }

    public static String getrandom1000() throws Exception {
        Random ra = new Random();
        return ra.nextInt(1000) + "";
    }

    /*
     * 获取当前时间（数据库格式）
     */
    public static String getnumTime() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");//可以方便地修改日期格式
        return dateFormat.format(now);
    }

    /*
     * 获取当前时间（年月日）
     */
    public static String getCurrentTime1() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//可以方便地修改日期格式
        return dateFormat.format(now);
    }

    public static Date getdate(int i) // //获取前后日期 i为正数 向后推迟i天，负数时向前提前i天
    {
        Date dat = null;
        Calendar cd = Calendar.getInstance();
        cd.add(Calendar.DATE, i);
        dat = cd.getTime();
        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp date = Timestamp.valueOf(dformat.format(dat));
        return date;
    }

    public static String getdate1(int i) // //获取前后日期 i为正数 向后推迟i天，负数时向前提前i天
    {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String getdate2(int i) // //获取前后日期 i为正数 向后推迟i天，负数时向前提前i天
    {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 获取明天的时间
     *
     * @return
     * @throws ParseException
     */
    public static String gettommorowtime() throws ParseException {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sf.format(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(sf.parse(nowDate));
        cal.add(Calendar.DAY_OF_YEAR, +1);
        String nextDate_1 = sf.format(cal.getTime());
        return nextDate_1;
    }


    public static String getdaytime(int day, String endtime) throws ParseException {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sf.format(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(sf.parse(nowDate));
        cal.add(Calendar.DAY_OF_YEAR, -(day - 1));
        String nextDate_1 = sf.format(cal.getTime());
        return nextDate_1 + endtime;
    }

    //获取前5秒的时间
    public static String getbeforetime(int second) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = new GregorianCalendar();
        Date date = new Date();
        c.setTime(date);//设置参数时间
        c.add(Calendar.SECOND, -second);//把日期往后增加SECOND 秒.整数往后推,负数往前移动
        date = c.getTime(); //这个时间就是日期往后推一天的结果
        String str = df.format(date);
        return str;
    }
    /*
     * 获取两个时间的差额
     */


    public static long getTimeDiff(String start, String end, String unit) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long adiff = 0;
        try {
            Date d1 = df.parse(start);
            Date d2 = df.parse(end);
            long diff = d2.getTime() - d1.getTime();
            if (unit.equals("day")) {

                adiff = diff / (1000 * 60 * 60 * 24);
            } else if (unit.equals("hour")) {
                adiff = diff / (1000 * 60 * 60);
            } else if (unit.equals("minute")) {
                adiff = diff / (1000 * 60);
            } else if (unit.equals("second")) {
                adiff = diff / 1000;
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return adiff;
    }

    //将秒转为时分秒
    public static String formatSecond(long seconds) {
        long hour = seconds / 3600;
        long minute = seconds % 3600 / 60;
        long second = seconds % 60;
        String times = hour + ":" + minute + ":" + second;
        return times;

    }

    public static String formatSecond2(long seconds) {
        long hour = seconds / 3600;
        long minute = seconds % 3600 / 60;
        long second = seconds % 60;
        String times = hour + "时" + minute + "分" + second + "秒";
        return times;

    }

    /**
     * 转换成分
     *
     * @param seconds
     * @return
     */
    public static String formatMinute(long seconds) {
        long hour = seconds / 3600;
        long minute = seconds % 3600 / 60;
        String times = hour + "时" + minute + "分";
        return times;

    }

    public static String formatSecond3(String seconds1) {
        Long seconds = Long.parseLong(seconds1);
        long hour = seconds / 3600;
        long minute = seconds % 3600 / 60;
        long second = seconds % 60;
        String times = hour + "时" + minute + "分" + second + "秒";
        return times;

    }

    public static String DatejianDate(String date1, String date2) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = sdf.parse(date1);
        Date d2 = sdf.parse(date2);
        Long seconds = d1.getTime() - d2.getTime();
        return (Math.ceil(seconds / (1000 * 60))) + "";
    }

    /**
     * 获取当前月份的时间范围
     *
     * @return
     */
    public static String getThisMonth() {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(Calendar.DAY_OF_MONTH, 1);
        setMinTime(startCalendar);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setMaxTime(endCalendar);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(startCalendar.getTime()) + ":" + formatter.format(endCalendar.getTime());
    }

    /**
     * 获取上个月的时间范围
     *
     * @return
     */
    public static String getLastMonth() {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.add(Calendar.MONTH, -1);
        startCalendar.set(Calendar.DAY_OF_MONTH, 1);
        setMinTime(startCalendar);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.add(Calendar.MONTH, -1);
        endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setMaxTime(endCalendar);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(startCalendar.getTime()) + ":" + formatter.format(endCalendar.getTime());
    }

    /**
     * 获取当前季度的时间范围
     *
     * @return current quarter
     */
    public static String getThisQuarter() {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(Calendar.MONTH, ((int) startCalendar.get(Calendar.MONTH) / 3) * 3);
        startCalendar.set(Calendar.DAY_OF_MONTH, 1);
        setMinTime(startCalendar);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(Calendar.MONTH, ((int) startCalendar.get(Calendar.MONTH) / 3) * 3 + 2);
        endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setMaxTime(endCalendar);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(startCalendar.getTime()) + ":" + formatter.format(endCalendar.getTime());
    }

    /**
     * 4舍5入
     *
     * @return
     */

    public static String fourFiveNumber(String number) {
        double num = 0.0;
        try {
            num = Double.parseDouble(number);
            if (num == 0.0) {
                return "0";
            }
            if (num < 1.0) {
                return num + "";
            }
            return "" + (new DecimalFormat("#.00").format(num));
        } catch (Exception e) {
            return "0";
        }
    }

    /**
     * 获取上个季度的时间范围
     *
     * @return
     */
    public static String getLastQuarter() {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(Calendar.MONTH, ((int) startCalendar.get(Calendar.MONTH) / 3 - 1) * 3);
        startCalendar.set(Calendar.DAY_OF_MONTH, 1);
        setMinTime(startCalendar);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(Calendar.MONTH, ((int) endCalendar.get(Calendar.MONTH) / 3 - 1) * 3 + 2);
        endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setMaxTime(endCalendar);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(startCalendar.getTime()) + ":" + formatter.format(endCalendar.getTime());
    }

    private static void setMinTime(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    private static void setMaxTime(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
        calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND));
    }

    public static String getdatebydate(String str, int i) {
        // 时间表示格式可以改变，yyyyMMdd需要写例如20160523这种形式的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 将字符串的日期转为Date类型，ParsePosition(0)表示从第一个字符开始解析
        Date date = sdf.parse(str, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // add方法中的第二个参数n中，正数表示该日期后n天，负数表示该日期的前n天
        calendar.add(Calendar.DATE, i);
        Date date1 = calendar.getTime();
        String out = sdf.format(date1);
        return out;
    }

    public static String createBigSmallLetterStrOrNumberRadom(int num) {

        String str = "";
        for (int i = 0; i < num; i++) {
            int intVal = (int) (Math.random() * 58 + 65);
            if (intVal >= 91 && intVal <= 96) {
                i--;
            }
            if (intVal < 91 || intVal > 96) {
                if (intVal % 2 == 0) {
                    str += (char) intVal;
                } else {
                    str += (int) (Math.random() * 10);
                }
            }
        }
        return str;
    }

    /**
     * @param num
     * @return
     * @author wangqing@9fbank.com 2015-6-26 下午2:51:44
     * @function 生成num位的随机字符串(数字 、 小写字母随机混排)
     */
    public static String createSmallStrOrNumberRadom(int num) {

        String str = "";
        for (int i = 0; i < num; i++) {
            int intVal = (int) (Math.random() * 26 + 97);
            if (intVal % 2 == 0) {
                str += (char) intVal;
            } else {
                str += (int) (Math.random() * 10);
            }
        }
        return str;
    }

    /**
     * @param num
     * @return
     * @author wangqing@9fbank.com 2015-6-26 下午2:51:44
     * @function 生成num位的随机字符串(小写字母与数字混排)
     */
    public static String createBigStrOrNumberRadom(int num) {

        String str = "";
        for (int i = 0; i < num; i++) {
            int intVal = (int) (Math.random() * 26 + 65);
            if (intVal % 2 == 0) {
                str += (char) intVal;
            } else {
                str += (int) (Math.random() * 10);
            }
        }
        return str;
    }


    public static String JsonRemoveSymbols(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if ((c >= 0 && c <= 31) || c == 127)//在ASCⅡ码中，第0～31号及第127号(共33个)是控制字符或通讯专用字符
            {

            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 获取上个月
     *
     * @return
     */
    public static String getPremonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String mon = format.format(m);
        return mon;
    }

    /**
     * 获取年月
     *
     * @param time
     * @return
     * @throws Exception
     */
    public static String getptyearmonth(String time) throws Exception {
        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sfd.parse(time);
        SimpleDateFormat sfd2 = new SimpleDateFormat("yyyyMM");
        return sfd2.format(d1);
    }

    /**
     * 获取本月上月
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        System.out.println(getHour(new Date()));
    }

    /***
     * 加星号隐藏手机号码
     * @param str
     * @return
     */
    public static String jiaxinghao(String str) {
        int len = str.length();
        if (len == 0) {
            return "***";
        } else {
            if (len <= 3) {
                str = str.substring(0, 1) + "**";
            } else if (len <= 5) {
                str = str.substring(0, len - 3) + "**" + str.substring(len - 1);
            } else if (len == 6) {
                str = str.substring(0, 2) + "**" + str.substring(len - 2);
            } else if (len > 6) {
                str = str.substring(0, 3) + "**" + str.substring(len - 4);
            }
            return str;
        }
    }

    public static String getHour(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
    }


    /*
     * 获取当前日期（数据库格式）
     */
    public static String getCurrentDay() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(now);
    }


    public static String getAfterMonth(String inputDate, int number) {
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(inputDate);//初始日期
        } catch (Exception e) {

        }
        c.setTime(date);//设置日历时间
        c.add(Calendar.MONTH, number);//在日历的月份上增加6个月
        String strDate = sdf.format(c.getTime());//的到你想要得6个月后的日期
        return strDate;
    }


    /**
     * 把long 转换成 日期 再转换成String类型
     * @param dateFormat
     * @param millSec
     * @return
     */
    public static String transferLongToDate(String dateFormat, Long millSec) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date = new Date(millSec);
        return sdf.format(date);
    }

    //半角转全角：（英文符号转为中文符号）
    public static String ToSBC(String input) {
        char[] c=input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i]==32)
            {
                c[i]=(char)12288; continue;
            }
            if (c[i]<127) c[i]=(char)(c[i]+65248);
        }
        return new String(c);
    }

    //全角转半角：(中文符号转英文符号)
    public static String ToDBC(String input) {
        char[] c=input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i]==12288)
            {
                c[i]= (char)32; continue;
            }
            if (c[i]>65280 && c[i]<65375)
                c[i]=(char)(c[i]-65248);
        }
        return new String(c);
    }

}

